<!--
 * @Descripttion: 
 * @version: 
 * @@Company: DCIT-SH
 * @Author: 王富银
 * @Date: 2024-08-20 22:49:28
 * @LastEditors: Sunny Chen
 * @LastEditTime: 2024-08-21 18:00:03
-->
<template>
  <div class="login">
    <div class="login-control">
      <div class="control-item">
        <span>用户名:</span>
        <el-input
          v-model="userName"
          style="width: 240px"
          placeholder="请输入用户名"
        />
      </div>
      <div class="control-item">
        <span>密&nbsp;&nbsp;&nbsp;码:</span>
        <el-input
          v-model="userPsw"
          style="width: 240px"
          type="password"
          placeholder="请输入密码"
          show-password
        />
      </div>
      <div>
        <el-button type="primary" @click="loginByNameAndPsw">登录</el-button>
        <el-button type="success">注册</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { login } from "@/api/api";
import { ElMessage } from "element-plus";
import  {useRouter} from 'vue-router'
import {usePostStore} from '@/stores';
const emits = defineEmits(['loginSuccess'])
const stores = usePostStore();
const {updateCurrentLoginName,updateCurrentLoginType} = stores;
const router = useRouter();
const userName = ref("admin");
const userPsw = ref("123456");
const loginByNameAndPsw = async () => {
  const name = userName.value;
  const psw = userPsw.value;
  const params = {
    name: name,
    psw: psw,
  };
  const res = await login(params);
  if (res.length) {
    //将token写入内存中
    sessionStorage.setItem("token", res[0].name + "-" + res[0].psw);
    ElMessage({message:"登录成功",type:'success'})
    router.push({path:"/"});
    updateCurrentLoginName(name);
    const type = res[0].type;
    updateCurrentLoginType(type);
    emits('loginSuccess');
  } else {
    ElMessage({ message: "用户不存才或密码错误", type: "error" });
  }
};
</script>

<style scoped>
.login {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 100%;
  height: 100%;
  background-color: white;
}
.login .login-control {
  width: 500px;
  height: 500px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  border: 1px solid #4ed479;
  border-radius: 40px;
}
.login .login-control .control-item {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}
</style>
